//
//  WzCitySearchViewController.m
//  B
//
//  Created by 王展 on 15/11/11.
//  Copyright © 2015年 wangzhan. All rights reserved.
//

#import "WzCitySearchViewController.h"
#import "WzCity.h"

@interface WzCitySearchViewController ()<UISearchResultsUpdating,UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong)UISearchController *searchController;
@property(nonatomic,strong)UITableView *citysearchTV;
@property(nonatomic,strong)NSMutableArray *cityArray;

@property(nonatomic,strong)NSMutableArray *searchArray;

@end

@implementation WzCitySearchViewController

- (void) viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    for (UIView *view in self.tabBarController.view.subviews) {
        if ([view isKindOfClass:[BaseView class]]) {
            view.hidden = YES;
        }
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    for (UIView *view in self.tabBarController.view.subviews) {
        if ([view isKindOfClass:[BaseView class]]) {
            view.hidden = NO;
        }
    }
    
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}

-(void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonAction)];
    
    [self createSearchController];
    [self createCitySearchTV];
    [self addSearchCityRefresh];
}

-(void)leftBarButtonAction
{
    [self.navigationController popViewControllerAnimated:NO];
    [self.myAgent LeftButtonAction];
}

-(void)addSearchCityRefresh
{
    self.citysearchTV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self getCityIDdata];
        
    }];
    
    [self.citysearchTV.header beginRefreshing];
}


-(void)createSearchController
{
    //创建UISearchcontroller
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.navigationItem.titleView = self.searchController.searchBar;
    self.searchController.searchResultsUpdater = self;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.searchBar.placeholder = @"搜索音乐";
    self.searchController.searchBar.tintColor = [UIColor colorWithRed:43 / 255.0 green:130 /255.0 blue:199 / 255.0 alpha:1];
    self.searchController.searchBar.barStyle = UIBarStyleBlack;
    
    self.searchController.searchBar.showsCancelButton = NO;
    [self.searchController.searchBar sizeToFit];
}

-(void)createCitySearchTV
{
    self.citysearchTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT - 64) style:UITableViewStylePlain];
    self.citysearchTV.delegate = self;
    self.citysearchTV.dataSource = self;
    [self.view addSubview:self.citysearchTV];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchController.active) {
        return self.searchArray.count;
    }
    else{
    return self.cityArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    WzCity *city = [[WzCity alloc] init];
 
    if (self.searchController.active) {
        city = [self.searchArray objectAtIndex:indexPath.row];
    }else{
        city = [self.cityArray objectAtIndex:indexPath.row];
    }
    
    cell.textLabel.text = city.citynm;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.citysearchTV deselectRowAtIndexPath:indexPath animated:YES];
    
    WzCity *city = [[WzCity alloc] init];
    if (self.searchController.active) {
        city = [self.searchArray objectAtIndex:indexPath.row];
    }else
    {
        city = [self.cityArray objectAtIndex:indexPath.row];
    }
   
    
    [self.myAgent giveCityID:city.cityno];
    
    [self.navigationController popViewControllerAnimated:NO];
}


-(void)getCityIDdata
{
    NSString *url_string = [NSString stringWithFormat:@"http://api.k780.com:88/?app=weather.city&&appkey=154443&sign=0ae11d1a1780cbd0d768f016c19a8a1c&format=json"];
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        self.cityArray = [NSMutableArray array];
//        NSLog(@"使用AFN进行get请求 ===  %@",responseObject);
        NSDictionary *bigDic = responseObject;
        NSDictionary *resultDic = [bigDic objectForKey:@"result"];
        for (int i = 1; i <= 2645; i++) {
            NSString *key = [NSString stringWithFormat:@"%d",i];
            NSDictionary *dic = [resultDic objectForKey:key];
            WzCity *city = [[WzCity alloc] init];
            [city setValuesForKeysWithDictionary:dic];
            [self.cityArray addObject:city];
        }
        
        NSLog(@"%ld",self.cityArray.count);

        [self.citysearchTV.header endRefreshing];
        [self.citysearchTV reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];

}




-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    NSLog(@"%@",searchString);
    
    self.searchArray = [NSMutableArray array];
    
    for (WzCity *city in self.cityArray) {
        if ([city.citynm containsString:searchString]) {
            [self.searchArray addObject:city];
        }
    }
    
    [self.citysearchTV reloadData];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
